//
//  NetworkTools.swift
//  JKWeiBo
//
//  Created by 王冲 on 2017/8/20.
//  Copyright © 2017年 希爱欧科技有限公司. All rights reserved.
//

import UIKit

import AFNetworking

enum JKMethodType : String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {

    
    static let tools: NetworkTools = {
    
        // 注意: baseURL一定要以 / 结尾
        let url = NSURL(string: "https://api.weibo.com/")
        let t = NetworkTools(baseURL: url! as URL)
        t.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript","text/plain") as? Set<String>
        return t
        
    }()
    
    // 获取单粒方法
    class func shareNetworkTools() -> NetworkTools {
        
        return tools
    }
    
    // 定义闭包别名
    typealias Finished = (_ result : [String : AnyObject]?, _ error : NSError?) -> ()
}

// MARK:- 网络请求的封装
extension NetworkTools {

    func request(methodType : JKMethodType , urlString : String, parameters: [String : AnyObject], finished : @escaping (_ result : Any?, _ error : Error?) -> ()) {
        
        // 1.封装成功的回调
        let successCallBack = { (task : URLSessionDataTask, result : Any?) -> Void in
            finished(result, nil)
        }
        
        // 2.封装失败的回调
        let failureCallBack = { (task : URLSessionDataTask?, error : Error) -> Void in
            finished(nil, error)
        }
        
        // 3.发送网络请求
        if methodType == .GET {

            get(urlString, parameters: parameters, progress: nil, success: successCallBack , failure: failureCallBack)
        } else {
            
            post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
        
    }
}

extension NetworkTools{
    
    // MARK: 1.发送微博
    func sendStatus(statusText : String, image : UIImage?, isSuccess : @escaping (_ isSuccess : Bool) -> ()) {
        // 0.获取accessToken
        guard let accessToken = UserAccount.loadAccount()?.access_token else {
            return
        }
        
        // 1.获取请求参数
        let params = ["access_token" : accessToken, "status" : statusText]
        
        // 2.获取URLString
        let urlString = "2/statuses/update.json"
            
        // 3.发送网络请求
        request(methodType: .POST, urlString: urlString, parameters: params as [String : AnyObject]) { (result, error) -> () in
            
            if error != nil
            {
                isSuccess(false)
                
            } else {
                
                isSuccess(true)
                
            }
        }
        
    }
    
}

